package top.malaoshi.webmvc;

import org.springframework.beans.factory.annotation.Value;
import top.malaoshi.sprout.ioc.DefaultSingletonBeanRegistry;
import top.malaoshi.util.StringUtil;
import top.malaoshi.webmvc.info.FieldInfo;

import java.lang.reflect.Field;

/**
 * 将 @Value 注解修饰的成员变量，将配置文件中的数据注入到成员变量中
 */
public class ValueAnnotationHandler {
    private DefaultSingletonBeanRegistry registry = DefaultSingletonBeanRegistry.me();

    private static final String START = "${";
    private static final String END = "}";

    public void handle() throws Exception {
        registry.forEachClassInfos(classInfo -> {
            String beanName = classInfo.getName();
            Object bean = registry.getEarlySingletonObject(beanName);
            if(bean==null){
                return;
            }

            for(FieldInfo fi : classInfo.getFieldInfos()){
                Value valueAnn = fi.getValue();
                if(valueAnn!=null){
                    String originValue = valueAnn.value();
                    if(originValue.startsWith(START) && originValue.endsWith(END)){
                        String key = StringUtil.slice(originValue,START.length(),-1);
                        Object value = ApplicationConfigFileReader.getValue(key);
                        Field field = fi.getField();
                        field.setAccessible(true);
                        Class<?> type = field.getType();
                        if(type == String.class ){
                            if(value == null){

                            }else if( value instanceof String){

                                field.set(bean,value);
                            }else {
                                field.set(bean, "" + value);
                            }
                        }else{

                            field.set(bean,value);
                        }
                    }else{
                        throw new Exception(originValue+"格式错误，应该是 ${xxx} 格式");
                    }
                }
            }

        });
    }
}
